package com.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.project.entity.Rider;
import com.project.entity.WithDraw;
import com.project.mapper.IWithDrawMapper;
import com.project.mapper.TRiderMapper;
import com.project.service.IRiderRemoteService;
import lombok.With;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping("/withdraw")
public class WithDrawController {

    @Autowired
    private IWithDrawMapper mapper;
    @Autowired
    private TRiderMapper riderMapper;
    @Autowired
    private IRiderRemoteService riderRemoteService;

    @GetMapping("count")
    public int count(){
        QueryWrapper<WithDraw> wrapper = new QueryWrapper<>();
        wrapper.eq("w_status",0);
        return mapper.selectList(wrapper).size();
    }

    @GetMapping("withdraw")
    public List<WithDraw> withdraw(int num){
        QueryWrapper<WithDraw> wrapper = new QueryWrapper<>();
        wrapper.eq("w_status",num);

        List<WithDraw> withDraws = mapper.selectList(wrapper);
        for (int i = 0; i < withDraws.size(); i++) {
            WithDraw withDraw = withDraws.get(i);
            String riderCode = withDraw.getRiderCode();
            QueryWrapper<Rider> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("r_code",riderCode);
            Rider rider = riderMapper.selectOne(wrapper1);
            withDraw.setRider(rider);
            withDraws.set(i,withDraw);
        }
        return withDraws;
    }

    @PostMapping("finish")
    public String finish(int id){
        try {
            DateTimeFormatter dfDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            WithDraw withDraw = mapper.selectById(id);
            withDraw.setEndTime(dfDate.format(LocalDateTime.now()));
            withDraw.setStatus(1);
            UpdateWrapper<WithDraw> wrapper = new UpdateWrapper<>();
            wrapper.eq("pk_withdrawId",id);

            riderRemoteService.update(withDraw.getRiderCode(),withDraw.getMoney());
            mapper.update(withDraw,wrapper);
            return "ok";
        } catch (Exception e) {
            return "no";
        }
    }
}
